package com.zmj.dubboannotation.consumermobile.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.zmj.commoncore.constant.RedisConstant;
import com.zmj.commoncore.dto.CartDTO;
import com.zmj.commoncore.utils.IpUtil;
import com.zmj.commoncore.utils.MemberIdUtil;
import com.zmj.dubboannotation.consumermobile.redis.RedisUtil;
import com.zmj.dubboannotation.serviceapi.api.CartService;
import com.zmj.dubboannotation.serviceapi.enums.ResultEnum;
import com.zmj.dubboannotation.serviceapi.utils.ResultVOUtil;
import com.zmj.dubboannotation.serviceapi.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;

/**
 * 购物车控制层
 * Created by: meijun
 * Date: 2018/10/30 14:26
 */
@RestController
@Api(value = "CartController", description = "购物车接口")
@RequestMapping("/cart")
public class CartController extends BaseController {

    @Autowired
    private RedisUtil redisUtil;

    @Reference
    private CartService cartService;

    /**
     * 获取购物车列表
     * @return
     */
    @ApiOperation(value = "购物车购买",notes = "购物车提交订单")
    @ApiImplicitParam(name = "checked", value = "获取购物车列表,默认获取全部", required = false, dataType = "Boolean")
    @GetMapping
    public ResultVO get(HttpServletRequest request,@RequestParam(defaultValue = "true",required = true) boolean checked){
        String memberId = MemberIdUtil.getCookieMemberId(request);
        return  this.resultCartList(memberId, checked);
    }

    /**
     * 商品加入购物车
     * 以店铺-->商品/商品商品存放
     * @param cartDTO
     * @return
     */
    @ApiOperation(value = "商品加入购物车",notes = "商品加入购物车")
    @PostMapping
    public ResultVO create(@Valid CartDTO cartDTO, HttpServletRequest request) {
        String memberId = MemberIdUtil.getCookieMemberId(request);

        if(StringUtils.isNotBlank(memberId)) {
            cartDTO.setMemberId(memberId);
            Map<Object, Object> cart = redisUtil.getHashEntries(RedisConstant.MEMBER_CART + memberId);
            if(null == cart || cart.size() == 0) {
                //如果购物车为空则按店铺分类 在按商品id加规格值分类存入购物车
                JSONObject jsonObject = new JSONObject();
                jsonObject.put(cartDTO.getProductId() + "-" + cartDTO.getAttrValueId(),cartDTO);
                redisUtil.put(RedisConstant.MEMBER_CART + memberId,String.valueOf(cartDTO.getShopId()),jsonObject.toJSONString());
            }else {
                //如果购物车不为空则获取是否存在该店铺
                Object obj = cart.get(String.valueOf(cartDTO.getShopId()));
                if(null != obj) {
                    JSONObject jsonObject = JSONObject.parseObject(obj.toString());
                    //如果存在该店铺,则根据商品id和规格值查询购物车是否存在该商品
                    JSONObject object = jsonObject.getJSONObject(cartDTO.getProductId() + "-" + cartDTO.getAttrValueId());
                    //如果存在该商品 , 则增加数量
                    if(null != object) {
                        CartDTO cartDTO2 = JSONObject.toJavaObject(object, CartDTO.class);
                        cartDTO2.setQuantity(cartDTO2.getQuantity() + 1);
                        jsonObject.put(cartDTO.getProductId() + "-" + cartDTO.getAttrValueId(),cartDTO2);
                        redisUtil.put(RedisConstant.MEMBER_CART + memberId,String.valueOf(cartDTO.getShopId()),jsonObject.toJSONString());
                    }else {
                        //如果不存在该商品 则加入缓存
                        jsonObject.put(cartDTO.getProductId() + "-" + cartDTO.getAttrValueId(),cartDTO);
                        redisUtil.put(RedisConstant.MEMBER_CART + memberId,String.valueOf(cartDTO.getShopId()),jsonObject.toJSONString());
                    }

                }else {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put(cartDTO.getProductId() + "-" + cartDTO.getAttrValueId(),cartDTO);
                    redisUtil.put(RedisConstant.MEMBER_CART + memberId,String.valueOf(cartDTO.getShopId()),jsonObject.toJSONString());
                }
            }
        }else{
            String ipAddr = IpUtil.getIpAddr(request);
            //TODO  未登陆账号加入购物车的逻辑 暂不实现

        }
        return ResultVOUtil.success(ResultEnum.ADD_CART_MSG.getMsg());
    }

    /**
     * 购物车商品加减
     *
     * @param cartDTO
     * @return
     */
    @ApiOperation(value = "购物车商品加减",notes = "购物车商品加减")
    @PutMapping
    public ResultVO update(CartDTO cartDTO,HttpServletRequest request) {
        String memberId = MemberIdUtil.getCookieMemberId(request);
        Map<Object, Object> cart = redisUtil.getHashEntries(RedisConstant.MEMBER_CART + memberId);

        if (null != cart || cart.size() > 0) {
            //如果购物车不为空则获取是否存在该店铺
            Object obj = cart.get(String.valueOf(cartDTO.getShopId()));
            if(null != obj) {
                JSONObject jsonObject = JSONObject.parseObject(obj.toString());
                //如果存在该店铺 直接根据skuProductId查询
                JSONObject object = jsonObject.getJSONObject(cartDTO.getSkuProductId());
                //如果存在该商品 ,修改为本次的数量
                if(null != object) {
                    CartDTO cartDTO2 = JSONObject.toJavaObject(object, CartDTO.class);
                    cartDTO2.setQuantity(cartDTO.getQuantity());
                    jsonObject.put(cartDTO.getSkuProductId(),cartDTO2);
                    redisUtil.put(RedisConstant.MEMBER_CART + cartDTO.getMemberId(),String.valueOf(cartDTO.getShopId()),jsonObject.toJSONString());

                    return ResultVOUtil.success(ResultEnum.ADD_CART_MSG.getMsg());
                }
            }
        }
        return ResultVOUtil.error(ResultEnum.REDIS_ADD_CART_ERROR);
    }


    /**
     * 购物车删除商品
     * @param cartDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "购物车删除商品",notes = "购物车删除商品")
    @DeleteMapping
    public ResultVO delete(CartDTO cartDTO,HttpServletRequest request) {
        String memberId = MemberIdUtil.getCookieMemberId(request);
        Map<Object, Object> cart = redisUtil.getHashEntries(RedisConstant.MEMBER_CART + memberId);

        if (null != cart && cart.size() > 0) {
            //如果购物车不为空则获取是否存在该店铺
            Object obj = cart.get(String.valueOf(cartDTO.getShopId()));
            if(null != obj) {
                JSONObject jsonObject = JSONObject.parseObject(obj.toString());
                //如果存在该店铺 直接根据skuProductId查询
                JSONObject object = jsonObject.getJSONObject(cartDTO.getSkuProductId());
                //如果存在该商品 ,修改为本次的数量
                if(null != object) {
                    //删除该商品
                    jsonObject.remove(object);
                }
                //删除以后该店铺下没有商品 则将该店铺删除
                if(null == jsonObject || jsonObject.size() == 0) {
                    cart.remove(obj);
                }
            }

            if(null == cart || cart.size() == 0) {
                //如果整个购物车都为空了 删除该缓存
                redisUtil.delete(RedisConstant.MEMBER_CART + memberId);
            }else {
                //如果购物车还有商品 删除对应 hashKey 下的商品
                redisUtil.delete(RedisConstant.MEMBER_CART + memberId,String.valueOf(cartDTO.getShopId()));
            }

            return ResultVOUtil.success(ResultEnum.ADD_CART_MSG.getMsg());
        }
        return ResultVOUtil.error(ResultEnum.REDIS_ADD_CART_ERROR);
    }


    @ApiOperation(value = "删除选中商品",notes = "删除选中商品")
    @DeleteMapping("/del")
    public ResultVO del(HttpServletRequest request) {
        String memberId = MemberIdUtil.getCookieMemberId(request);
        Map<Object, Object> cart = redisUtil.getHashEntries(RedisConstant.MEMBER_CART + memberId);
        int i = cartService.deleteChecked(cart, memberId);
        return ResultVOUtil.success(i);
    }

    public ResultVO resultCartList(String memberId, boolean checked) {
        Map<Object, Object> cart = redisUtil.getHashEntries(RedisConstant.MEMBER_CART + memberId);
        if(null != cart && cart.size() > 0 ) {
            JSONObject result = cartService.cartList(cart, checked);
            return ResultVOUtil.success(result);
        }
        return ResultVOUtil.error(ResultEnum.CART_EMPTY.getMsg());
    }

}
